package logutils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FileHandler {
	public boolean create(File file) 
	throws IOException{
		boolean success = false;
		try {
	        success = file.createNewFile();
	    } catch (IOException e) {
	    	System.out.println("caught in create file"+ e);
	    }
	    return success;
	}
	public ArrayList<String> read(File fileName, ArrayList<String> toRead)
	throws FileNotFoundException, IOException {
		ArrayList<String> file = new ArrayList<String>();
		if (fileName == null) {
			throw new IllegalArgumentException("File should not be null.");
		}
		if (!fileName.exists()) {
			throw new FileNotFoundException("File does not exist: " + fileName);
		}
		if (!fileName.isFile()) {
			throw new IllegalArgumentException("Should not be a directory: "
					+ fileName);
		}
		try {
			FileReader fr = new FileReader(fileName);
			BufferedReader br = new BufferedReader(fr);
			String s;
			while((s = br.readLine()) != null) {
				file.add(s);
			} 
			
		} catch (IOException e){
			System.out.println("IOException:");
            e.printStackTrace();		
		}
		
		
		return file;		
	}

	public boolean write(File fileName, List<String> toWrite)
			throws FileNotFoundException, IOException {
		/* taken from http://www.javapractices.com/topic/TopicAction.do?Id=42 */
		if (fileName == null) {
			throw new IllegalArgumentException("File should not be null.");
		}
		if (!fileName.exists()) {
			try {
				create(fileName);
			}catch (IOException e ) {
				System.err.println("Failed to create file: "+ e.getMessage());
				return false;
			}
		}
		if (!fileName.isFile()) {
			throw new IllegalArgumentException("Should not be a directory: "
					+ fileName);
		}

		Writer output = null;
		try {
			output = new BufferedWriter(new FileWriter(fileName));
			Iterator<String> s = toWrite.iterator();
			while (s.hasNext()) {
							output.write(s.next());
							output.write("\n");
			}
		} finally {

			if (output != null)
				output.close();
		}
		return true;
	}
}
